package com.witframework.core.message;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class MessageCacheManager {
	private static int MAXSIZE=10000;

	private static int MAXLIVETIME=30000;//s
	protected final static MessageCacheManager singleton = new MessageCacheManager();

	protected final Map<String, UIMessage> caches = new Hashtable<String, UIMessage>((int)(MAXSIZE*1.25));
	public static MessageCacheManager getInstance() {
        return singleton;
    }
	public void store(UIMessage message){
		if(caches.size()>MAXSIZE){
			manage();
		}
		caches.put(message.getId(), message);
	}

	public String[] getText(String key){
		int type=1;
		StringBuffer sb=new StringBuffer();
		String[] ids=key.split(",");
		for(String id:ids ){
			UIMessage message=caches.get(id);
			if(message!=null){
					sb.append(message.getMsg());
					sb.append(" ");
					type=message.getType();
					caches.remove(id);
				}
		}
		if(sb.length()>0)
			return new String[]{String.valueOf(type),sb.toString()};
		return null;
	}

	public String[] getMessage(String key){
		UIMessage message=caches.get(key);
		if(message!=null){
			caches.remove(key);
			return new String[]{String.valueOf(message.getType()),message.getMsg()};
		}
		return null;
	}

	public UIMessage[] get(String key){
		List ml=new ArrayList();
		String[] ids=key.split(",");
		for(String id:ids ){
			ml.add(caches.get(id));
			caches.remove(id);
		}
		return (UIMessage[]) ml.toArray(new UIMessage[0]);
	}

	private void manage(){
		long ct=System.currentTimeMillis();
		for(Iterator iterator=caches.entrySet().iterator();iterator.hasNext();){
			UIMessage message=(UIMessage)iterator.next();
			if(ct-message.getCreatTime()>MAXLIVETIME){
				iterator.remove();
			}
		}
		if(caches.size()>MAXSIZE){
			UIMessage[] keys=caches.entrySet().toArray(new UIMessage[0]);
			Arrays.sort(keys);
			for(int i=0;i<MAXSIZE-caches.size();i++){
				caches.remove(keys[i].getId());
			}
		}
	}
}
